import './lib/vue.js'

const gridSize = 32

const vue = new Vue({
  el: '#app',
  data: {
    width: 30,
    height: 20,
    gridItems: [],
    currentIndex: 0,
    landItems: [],
    currentLand: {
      src: '',
      name: ''
    },
    currentBorder: {
      src: '',
      name: ''
    },
    borderItems: [],
    isGridListShow: false,
    isBorderListShow: false,
    mapGrids: [],
    hasDrawMap: false,
    painting: false,
    canvas: {},
    context: {},
    mapName: '',
    mapId: 0,
    enemyBots: [],
    playerBots: []
  },
  created() {
    this.getMapDatas()
  },
  mounted() {
    this.canvas = this.$refs.canvas
    this.context = this.canvas.getContext('2d')
    this.drawAllGrid()
  },
  methods: {
    setCurrentIndex(index) {
      this.currentIndex = index
    },
    async getMapDatas() {
      const result = await axios.get('/getAllMapGrid')
      this.gridItems = result.data
      this.landItems = result.data.filter(e => e.name.includes('平地') || e.name.includes('海') || e.name.includes('沙') || e.name.includes('地板'))
      this.currentLand = this.landItems[0]
      this.borderItems = result.data.filter(e => e.name.includes('墙'))
      this.currentBorder = this.borderItems[0]

      //   this.autoLoad()
    },
    generateMapId() {
      const now = new Date()
      let year = now.getFullYear()
      let month = now.getMonth() + 1
      month = month < 10 ? '0' + month : month
      let day = now.getDate()
      day = day < 10 ? '0' + day : day
      let hour = now.getHours()
      hour = hour < 10 ? '0' + hour : hour
      let minute = now.getMinutes()
      minute = minute < 10 ? '0' + minute : minute
      let second = now.getSeconds()
      second = second < 10 ? '0' + second : second
      let random = Math.floor(Math.random() * 9000 + 1000)
      return `${year}-${month}-${day}-${hour}-${minute}-${second}-${random}`
    },
    createMap() {
      if (this.hasDrawMap) {
        if (!confirm('已经存在地图数据了，你确定要重新生成吗？')) return alert('取消重新生成')
      }
      this.mapId = this.generateMapId()
      this.hasDrawMap = true
      const row = this.width - 1
      const col = this.height - 1
      if (row < 4 || col < 4) {
        return alert('地图宽高要大点')
      }
      for (let i = 0; i <= row; i++) {
        this.mapGrids[i] = []
        for (let j = 0; j <= col; j++) {
          const img = new Image()
          this.mapGrids[i][j] = img
          if (i == 0 || i == row || j == 0 || j == col) {
            img.src = this.currentBorder.src
            img.id = this.currentBorder.id
          } else {
            img.src = this.currentLand.src
            img.id = this.currentLand.id
          }
        }
      }
      this.drawMap()
    },
    drawMap() {
      const width = this.width * gridSize
      const height = this.height * gridSize
      const canvas = this.$refs.canvas
      canvas.width = width
      canvas.height = height
      this.drawAllGrid()
    },
    drawAllGrid() {
      this.mapGrids.forEach((arr, x) => {
        arr.forEach((img, y) => {
          this.context.drawImage(img, x * gridSize, y * gridSize, gridSize, gridSize)
        })
      })
    },
    changeBorder(item) {
      this.currentBorder = item
      this.isBorderListShow = !this.isBorderListShow
    },
    changeLand(item) {
      this.currentLand = item
      this.isGridListShow = !this.isGridListShow
    },
    clickToPaint(e) {
      this.painting = true
      this.paintGrid(e)
    },
    paintGrid(e) {
      if (!this.painting || !this.hasDrawMap) return
      const mx = e.offsetX
      const my = e.offsetY
      const x = Math.floor(mx / gridSize)
      const y = Math.floor(my / gridSize)
      const img = new Image()
      img.src = this.gridItems[this.currentIndex].src
      img.id = this.gridItems[this.currentIndex].id
      this.mapGrids[x][y] = img
      this.context.drawImage(img, x * gridSize, y * gridSize, gridSize, gridSize)
    },
    autoSave() {
      setInterval(() => {
        if (this.mapGrids?.length == 0) return
        const temp = this.mapGrids.map(arr => arr.map(e => e.id))
        const json = JSON.stringify(temp)
        localStorage.setItem('mapGrids', json)
      }, 5000)
    },
    autoLoad() {
      const json = localStorage.getItem('mapGrids')
      console.log(json)
      if (json) {
        this.hasDrawMap = true
        const temp = JSON.parse(json).map(arr =>
          arr.map(id => {
            console.log(id)
            const img = new Image()
            img.src = this.gridItems.find(e => e.id == id).src
            img.id = id
            return img
          })
        )

        this.mapGrids = temp
        setTimeout(() => {
          this.drawAllGrid()
        }, 100)
      }
    },
    async saveMapHandler() {
      const mapIds = this.mapGrids.map(array => {
        return array.map(tile => parseInt(tile.id))
      })
      console.log(this.mapId)
      console.log(mapIds)
      const result = await axios.post('/saveLevelMap', {
        mapId: this.mapId,
        mapIds,
        mapName: this.mapName,
        enemyBots: this.enemyBots,
        playerBots: this.playerBots
      })
      console.log(result)
    }
  }
})

console.log(vue)
